package com.baor.utils;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
// 百度AI开放平台获取access_token
public class AccessTokenUtil {

    @Value("${baidu.appKey}")
    private String appKey;

    @Value("${baidu.appSecret}")
    private String appSecret;

    @Value("${baidu.tokenUrl}")
    private String tokenUrl;

    @Value("${baidu.grantType}")
    private String grantType;

    public String getAccessToken() {
        try {
            URL url = new URL(tokenUrl + "?grant_type=" + grantType + "&client_id=" + appKey + "&client_secret=" + appSecret);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 解析返回的JSON数据，获取access_token的值
                String jsonResponse = response.toString();
                // 使用你喜欢的JSON库解析JSON数据，例如 org.json 或者 Gson
                // 假设使用 org.json，解析代码如下：
                // JSONObject jsonObject = new JSONObject(jsonResponse);
                JSONObject jsonObject = new JSONObject(jsonResponse);
                String accessToken = jsonObject.getString("access_token");
                return accessToken;
            } else {
                // 请求失败，进行异常处理
                return null;
            }
        } catch (IOException e) {
            // 进行异常处理
            return null;
        }
    }
}

